/**
 * 	 DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *   @author Colin Redmond
 *   Copyright (C) 2011 Colin Redmond
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package com.cred.industries.platform.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import com.cred.industries.core.database.DBConnectionManager;
import com.cred.industries.core.exceptions.ApplicationException;
import com.cred.industries.core.transferObj.result.ReturnCodes;
import com.cred.industries.platform.business.objects.CustomerRolesBO;
import com.cred.industries.platform.defines.Role;

/**
 * manages all DB interaction for the Customer Roles. It takes in 
 *  customerRole BO's to update/create the DB
 * Note this class has no modify so it is only accessible in this package
 */
class CustomerRolesMySQLDAO implements ICustomerRolesDAO {
	
	//private final static Logger logger = LoggerFactory.getLogger(CustomerRolesMySQLDAO.class);
	
	private static final String ROLE_PRIORITY = "rolePriority";
	private static final String ROLE_NAME = "roleName";
	private static final String CUSTOMER_NAME = "PersonaName";
	
	public CustomerRolesMySQLDAO() {

	}
	
	/* (non-Javadoc)
	 * @see com.cred.industries.platform.dao.ICustomerRolesDAO#findCustomerRoleByCustomerId(int)
	 */
	@Override
	public CustomerRolesBO findCustomerRoleByPersonaName(String personaName) {

		String sqlQuery = "SELECT * FROM customerRole WHERE " + CUSTOMER_NAME + " = ?";
		// Setup the connection with the DB
		try (Connection connect = DBConnectionManager.getInstance().getConnection();
				PreparedStatement preparedStatement = connect.prepareStatement(sqlQuery) ) {
						
			preparedStatement.setString(1, personaName);
			
			try (ResultSet resultSet = preparedStatement.executeQuery()) {
			
				CustomerRolesBO custRoles = new CustomerRolesBO(personaName);
				//adds all the roles to the customer Roles BO
				while(resultSet.next())	{
					String roleName = resultSet.getString(ROLE_NAME);
					custRoles.assignRole(Role.convert(roleName));
				}
				
				return custRoles;
			}
			
		} catch (SQLException e) {
			throw new ApplicationException(e, ReturnCodes.DATABASE_ERROR, "failed populating role with " + personaName);
		}
	}
	
	/* (non-Javadoc)
	 * @see com.cred.industries.platform.dao.ICustomerRolesDAO#insert(java.sql.Connection, com.cred.industries.platform.business.objects.CustomerRolesBO)
	 */
	@Override
	public void insert(Connection connect, CustomerRolesBO custRoles) {
		
		String sqlQuery = "INSERT INTO customerrole VALUES (?, ?)";
		
		try (PreparedStatement preparedStatement = connect.prepareStatement(sqlQuery)) {
			
			String personaName = custRoles.getCustomerPersonaName();
			//for each role we add it to the Db
			for(Role r : custRoles.getRoles()) {
				preparedStatement.setString(1, personaName);
				preparedStatement.setString(2, r.toString());	
				int rowsUpdated = preparedStatement.executeUpdate();
				if(rowsUpdated == 0) {
					throw new ApplicationException(ReturnCodes.DATABASE_ERROR, "failed to create customerRols " + personaName +  " no rows updated");
				}
			}
			
		} catch (SQLException e) {
			throw new ApplicationException(e, ReturnCodes.DATABASE_ERROR, "failed populating role with " + custRoles.getCustomerPersonaName());
		}
	}
	
	/* (non-Javadoc)
	 * @see com.cred.industries.platform.dao.ICustomerRolesDAO#getRoles()
	 */
	@Override
	public Map<String, Integer> getRoles() {
		
		Map<String, Integer> result = new HashMap<>();
		
		String sqlQuery = "SELECT * FROM role";
		try (Connection connect = DBConnectionManager.getInstance().getConnection();
				Statement statement = connect.createStatement();
				ResultSet resultSet = statement.executeQuery(sqlQuery)) {
			
			while(resultSet.next())	{
				int roleId = resultSet.getInt(ROLE_PRIORITY);
				String roleName = resultSet.getString(ROLE_NAME);
				
				result.put(roleName, roleId);
			}
			
			return result;
			
		} catch (SQLException e) {
			throw new ApplicationException(e, ReturnCodes.DATABASE_ERROR, "failed to get roles");
		}
	}
}
